
import React, { useEffect } from 'react'
import { useNavigate, useRoutes, useLocation } from 'react-router-dom'

type route = {
    path:string,
    element:React.ReactNode
    label?:string
    key?:string
    icon?:any
}

type Iroute = route&{
    children?:Array<Iroute>
}
export type Iroutes = Array<Iroute>

type Iguard = (key: string, routse: Iroutes,storage?:string) => React.ReactNode
declare global {
    interface Window{
        [k:string]:any
    }
}
/**
 * 
 * @param key {string} token对应存储在本地的key
 * @param routes {Iroutes} 路由的routes配置
 */
const useRoutesWithGuard: Iguard = (key, routes,storage='sessionStorage') => {
    let navigate = useNavigate()
    let Element = useRoutes(routes)
    let location = useLocation()
    // let token: string | null = sessionStorage.getItem(key);
    let token: string | null = window[storage].getItem(key);
    
    useEffect(() => {
        if (!token) {
            //没有token，跳转到login
            //如果访问的页面不是login，就跳转到login
            if (location.pathname !== '/login') {
                navigate('/login')
            }
        }else{
            if(location.pathname==='/login'){
                sessionStorage.removeItem('qf-token')
            }
        }
    })
    return Element
}

export default useRoutesWithGuard